package com.youmans.msm.controller;


import com.youmans.commonutils.R;
import com.youmans.commonutils.RandomUtil;
import com.youmans.msm.component.SmsComPonent;
import com.youmans.msm.service.MsmService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
public class MsmApiController {
    @Autowired
    private MsmService msmService ;
    @Autowired
    private SmsComPonent smsComPonent ;
    @Autowired
    private RedisTemplate<String,String> redisTemplate ;
    //发送手机验证码
    @GetMapping("/send/{phone}")
    public R sendCode(@PathVariable String phone){
        //从redis获取验证码
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return R.ok() ;
        }
//        如果获取不到，生成验证码，
        code = RandomUtil.getSixBitRandom();

        // 通过短信服务进行发送，通过整合短信服务进行发送
        try {
            msmService.send(phone,code);
            redisTemplate.opsForValue().set("guli_school:code:"+phone, code, 3, TimeUnit.MINUTES);
            return R.ok();
        }catch (Exception e){
            return R.error().message("发送短信失败");
        }
// 生成验证码放到redis里面，设置过期时间
    }
}
